<?php
namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\Request;
use think\facade\View;
use think\helper\Str;
use think\exception\ValidateException;


// 文档下载中心
class Document extends BaseController
{

    public function index()
    {
        return View::fetch();
    }


    public function load(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();

        $total = Db::table('o_document')
            ->count();

        $rows = Db::table('o_document')
            ->order('id', 'desc')
            ->page($get['page'], $get['limit'])
            ->select()
            ->toArray();
        foreach ($rows as &$v) {

            if ($v['complete_time'] == 0) {
                $v['complete_time'] = '---------';
            } else {
                $v['complete_time'] = date('Y-m-d H:i:s', $v['complete_time']);
            }
        }
        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }


    //+删除
    public function delete(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->post('id');

        try {

            $data = Db::name('document')
                ->where('id', 'in', $id)
                ->select()
                ->toArray();

            if (!Db::name('document')->where('id', 'in', $id)->delete()) {
                return $this->outputAjax('删除失败！');
            }

            foreach ($data as &$v) {

                $res = Db::name('temporary_members')->where('type', '=', $v['type'])->find();

                if ($res) {
                    Db::name('temporary_members')->where('type', '=', $v['type'])->delete();
                }
                
                @unlink(public_path().$v['url']);
            }
            return $this->outputAjax('删除成功！',0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    public function export(Request $request)
    {
        $id = $request->get('id');

        try {

            $inf = Db::name('document')
                ->where('id', '=', $id)
                ->find();

            if (!$inf) {
                return $this->outputAjax('参数错误！');
            }

            $file = public_path().$inf['url'];
            $content = get_csv_data($file);

            ob_end_clean ();
            set_time_limit(0);
            //设置程序运行内存
            ini_set('memory_limit', '4096M');

            $fileName = $inf['title'];
            header('Content-Encoding: UTF-8');
            header("Content-type:application/vnd.ms-excel;charset=UTF-8");
            header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');


            //打开php标准输出流
            $fp = fopen('php://output', 'a');

            //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            foreach ($content as &$v) {
                fputcsv($fp, $v);
            }
            flush();

        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }
}